<?php

namespace App\Admin\Controllers;

use App\Models\Banner;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class BannerController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('首页轮播');
            $content->description('图片要求750X300');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('首页轮播');
            $content->description('图片要求750X300');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('首页轮播');
            $content->description('图片要求750X300');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Banner::class, function (Grid $grid) {
            $grid->id('ID')->sortable();
            $grid->title('标题');
            $grid->img('图片')->display(function ($data) {
                if (!$data) {
                    return '';
                }
                return <<<DATA
<img src="/uploads/{$data}" 
style="max-width:360px;max-height:200px" class="img img-thumbnail">
DATA;
            });
            $grid->url('链接');
            $grid->status('首页显示')->display(function ($data){
                return $data?'是':'否';
            });


            $grid->sort('排序')->sortable();
            $grid->created_at('创建时间');
            $grid->updated_at('更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Banner::class, function (Form $form) {
            $form->text('title','标题');
            $form->text('url','链接地址');
            $form->number('sort','排序');
            $form->radio('status','首页显示')->options(['0' => '否', '1'=> '是'])->default('0');
            // 使用随机生成文件名 (md5(uniqid()).extension)
            $image=$form->image('img','轮播图');
            $image->move('banners');
            $image->uniqueName();

        });
    }
}
